76% completed
Here is a step-by-step system design for ChatGPT.
1. Problem Definition and Scope
We are designing a global-scale conversational AI system where users can chat with a Large Language Model (LLM). The system must manage conversation state, persistent history, and real-time text streaming.
-
Users: 100 Million+ Daily Active Users (DAU), split into Free and Plus (Paid) tiers.
-
Main Actions: Starting a chat, sending messages, receiving streaming responses, and viewing history.
-
Scope:
-
In Scope: Chat backend, context management, history storage, inference orchestration, and streaming delivery.
-
Out of Scope: Model training (we assume pre-trained weights exist), complex payment processing, and voice/video features (focus on text).
-
2. Clarify functional requirements
Must Have:
-
Real-time Streaming: Users see the AI response appear token-by-token (typewriter effect) to reduce perceived latency.
-
Context Awareness: The model "remembers" previous messages in the current active conversation.
-
History Management: Users can browse and reload past conversations.
-
Model Switching: Ability to route requests to different models (e.g., "GPT-3.5" for speed, "GPT-4" for reasoning).
-
Concurrency: The system must handle millions of simultaneous chat sessions.
Nice to Have:
-
Regenerate: Option to retry the last response.
-
Auto-Titles: Automatically generate a title for the chat based on the content.
-
Search: Ability to search through past chat history.
3. Clarify non-functional requirements
-
Target Users: 100 Million DAU.
-
Traffic Pattern: High sustained traffic with likely spikes during working hours.
-
Latency:
- Time To First Token (TTFT): < 1 second. (Critical for UX).
- Total Generation Time: Variable (10–30s), but must not time out.
-
Availability: 99.9% for the web application. The inference layer may degrade gracefully (e.g., "System at capacity" message) under extreme load.
-
Consistency: Strong consistency for the active chat session; eventual consistency for the conversation list.
-
Data Retention: Indefinite (until user deletes).
4. Back of the envelope estimates
- Traffic:
-
100M DAU.
-
Average user sends 20 messages/day.
-
Total requests = 100M * 20 = 2 Billion messages/day.
-
Average QPS:
QPS. -
Peak QPS: Assume 2x average ≈ 50,000 QPS.
-
Note: While 50k QPS sounds low for a web app, each request holds a connection open for seconds and consumes massive GPU compute.
-
- Storage:
-
Average message turn (User + AI)
2KB (compressed). -
Daily Storage:
TB/day. -
Yearly Storage: 4 TB * 365 ≈ 1.46 PB/year.
-
This is manageable with standard NoSQL sharding.
-
- Bandwidth:
- Text is small. The system is compute-bound (GPU limits), not I/O bound.
5. API design
We will use REST for standard management and Server-Sent Events (SSE) for the chat stream. SSE is ideal because the data flow is strictly one-way (server pushing tokens to client) after the initial POST.
1. Create Conversation
- POST /v1/conversations
- Body: { "model": "gpt-4" }
- Response: { "conversation_id": "uuid", "created_at": "timestamp" }
2. Send Message (Stream)
- POST /v1/conversations/{conversation_id}/messages
- Headers: Accept: text/event-stream
- Body: { "content": "Explain recursion." }
- Response: Stream of events:
- data: {"role": "assistant", "delta": "Recursion"}
- data: {"role": "assistant", "delta": " is"}
- data: [DONE]
3. Get History
- GET /v1/conversations/{conversation_id}
- Response: { "messages": [ { "role": "user", "content": "..." }, ... ] }
4. List Conversations
- GET /v1/conversations?limit=20&offset=0
- Response: [ { "id": "...", "title": "Programming Help", "last_updated": "..." }, ... ]
6. High level architecture
We decouple the Web Layer (stateful session management) from the Inference Layer (stateless, heavy compute).
-
Client: Web or Mobile app. Renders Markdown and handles the SSE connection.
-
API Gateway: Manages authentication, rate limiting (crucial for cost control), and SSL termination.
-
Chat Service: The "brain" of the application.
- Validates requests.
- Assembles the "Prompt" (fetches previous messages from Cache/DB).
- Forwards the prompt to the Model Gateway.
- Streams the response back to the client.
-
Context Cache (Redis): Stores the last
messages of active conversations. This avoids hitting the persistent DB for every new message turn. -
Model Gateway (Inference Scheduler): A queue-based service that manages GPU resources. It prioritizes "Plus" users and dispatches jobs to available workers.
-
GPU Workers: Servers running the LLM (e.g., using Triton or vLLM). They accept a text prompt and stream tokens back.
-
History DB (NoSQL): Durable storage for all chat logs.
7. Data model
We need a database optimized for high write throughput (appending messages) and efficient retrieval by conversation ID. DynamoDB or Cassandra is the best fit.
1. Conversations Table
- conversation_id (Partition Key): Unique ID.
- user_id (GSI): To list all chats for a specific user.
- title: Auto-generated summary.
- last_updated: Timestamp (for sorting in the UI).
2. Messages Table
- conversation_id (Partition Key): Groups all messages of a chat together.
- message_id (Sort Key): TimeUUID or Monotonic Counter to ensure order.
- role: Enum (user, assistant, system).
- content: Text (the message body).
Why NoSQL?
- Chat data is append-only.
- We almost always query "Get all messages for Conversation X".
- Horizontal scaling is trivial by sharding on conversation_id.
8. Core flows end to end
To understand how this system handles scale and latency, we must trace the lifecycle of the most critical operation: A User Sending a Message.
In a standard web app, a request flow is typically Synchronous (Request DB Response). In an LLM application, the flow is Asynchronous and Streaming. Inference is slow (taking 10+ seconds), and the model is stateless (it forgets everything immediately).
We will break this flow into five logical phases to see how we manage these constraints.
Phase 1: Ingestion & Gatekeeping (Fail Fast)
Goal: Validate requests early to protect expensive GPU resources.
- Request Entry: The user sends a
POSTrequest to the API Gateway with the payload:{ "conversation_id": "uuid", "message": "Explain recursion." } - Authentication & Rate Limiting:
- The Gateway validates the User's Session (JWT).
- It checks the Rate Limiter (e.g., Redis Token Bucket). If the user has exceeded their quota (e.g., 50 messages/3 hours), the request is rejected immediately (
429 Too Many Requests).
- Moderation Check:
- Before touching the complex LLM, the Chat Service passes the text to a lightweight, fast Moderation Model (like a BERT classifier).
- Logic: If the text violates safety rules (hate speech, self-harm), we reject it here. This saves money by not running the expensive LLM on bad requests.
- Semantic Cache (Optimization):
- The service checks a Vector Database (e.g., Pinecone) to see if this exact question was answered recently.
- Hit: Return the cached answer instantly (< 100ms).
- Miss: Proceed to the main flow.
Phase 2: Context Assembly (The "Memory" Layer)
Goal: Create the illusion of a continuous conversation for the stateless AI.
LLMs have no memory. If you ask "What is the capital?", the model does not know you previously said "I am visiting France." We must reconstruct the memory for every single turn.
- Fetching History:
- The Chat Service queries Redis (Context Cache) for the recent message history of this
conversation_id. - Fallback: If Redis is empty (e.g., resuming an old chat), it fetches the history from DynamoDB and warms up Redis.
- Prompt Engineering (The Payload):
- The service assembles the final JSON payload to send to the model. It typically looks like this:
[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hi, I'm learning coding."}, {"role": "assistant", "content": "That's great! What language?"}, {"role": "user", "content": "Explain recursion."} ]
- Sliding Window Strategy:
- Constraint: Models have a limit (e.g., 8,192 tokens).
- Logic: If the history is too long, the service drops the oldest user/assistant messages to make space for the new one, while always keeping the "System" instruction to maintain the persona.
Phase 3: Orchestration (The "Waiting Room")
Goal: Decouple web servers from GPU servers to manage load.
We cannot connect the Chat Service directly to GPU servers; a traffic spike would crash them. We need a buffer.
- Dispatch: The Chat Service sends the assembled prompt to the Model Gateway.
- Priority Queuing:
- The Model Gateway pushes the job into a Distributed Queue (e.g., Kafka or RabbitMQ).
- Tiered Access: "Plus" users go into a High-Priority Queue, while Free users go into a Standard Queue.
- Worker Pull: An idle GPU Worker pulls the job from the queue when it has capacity.
Phase 4: Inference & Streaming (The Execution)
Goal: Low latency perception.
We do not wait for the full answer to be ready. We stream it token-by-token.
- KV Cache Loading:
- Optimization: When the GPU Worker loads the prompt, it checks if it has the "Key-Value" attention matrices for this conversation cached in VRAM. If yes, it skips re-computing the math for the history part of the prompt.
- Token Generation: The model generates the response one token (approx. 0.75 words) at a time.
- The Stream Chain:
GPU WorkerModel GatewayChat ServiceClient- The Chat Service pushes tokens to the client using Server-Sent Events (SSE).
- User Experience: The user sees the text "typing out" in real-time. This keeps the Time To First Token (TTFT) under 1 second, even if the full answer takes 30 seconds.
Phase 5: Async Persistence (The Cleanup)
Goal: Save data reliably without blocking the user.
We never write to the disk database (DynamoDB) during the streaming phase. Database I/O is slow and could cause the stream to stutter.
-
Aggregation: Once the model sends the
[DONE]signal, the Chat Service combines all streamed tokens into a complete string. -
Fire-and-Forget Writes:
- Hot Storage: Append the new User Message and Assistant Response to the Redis list (updating the context for the next turn).
- Cold Storage: Asynchronously write the new messages to DynamoDB for permanent storage.
- Search Index: DynamoDB Streams triggers an update to Elasticsearch so the user can search this conversation later.
9. Caching and read performance
1. Context Cache (Redis):
-
Key: context:{conversation_id}
-
Value: List of recent message objects.
-
Strategy: LRU with 1-hour TTL.
-
Why: LLMs are stateless. We must re-send the history every time. Reading this from RAM (Redis) is much faster than Disk (DB).
2. Semantic Cache (Vector Store):
-
Store embedding of (prompt) -> (response).
-
If a user asks "What is the capital of France?", we return "Paris" from cache without burning expensive GPU cycles.
3. Model KV Cache (GPU VRAM):
-
Optimization: Inside the GPU worker, we cache the "Key-Value" matrices of the attention mechanism.
-
When a user adds a message to an existing chat, the GPU only computes the new tokens, reusing the computation for the history. This is standard in modern inference engines (like vLLM).
10. Storage, indexing and media
-
Primary Storage: DynamoDB (as described above).
-
Search Index (Elasticsearch):
- To allow users to "Search History", we use DynamoDB Streams to replicate new messages into an Elasticsearch cluster.
- Queries hit Elasticsearch, not the primary DB.
-
Media:
- If we support image generation or upload:
- Store binary files in S3 (Object Storage).
- Store the S3 URL in the content field of the message.
11. Scaling strategies
Scaling Inference (The Bottleneck):
-
Queue-Based Load Leveling: We cannot autoscale GPUs instantly (availability is scarce). We use queues to smooth out bursts.
-
Tiered Service:
- Plus Users: Routed to a reserved pool of GPUs.
- Free Users: Routed to a standard pool. During high load, we might route them to a smaller, faster model (e.g., "Turbo") to save compute.
-
Quantization: Serve models using 8-bit integers (INT8) instead of 16-bit floats (FP16) for free users. This reduces memory usage and increases throughput.
Scaling Database:
- DynamoDB scales linearly with the number of conversations. We provision Write Capacity Units (WCUs) based on peak load.
12. Reliability, failure handling and backpressure
- Backpressure:
- If the Model Gateway queue depth exceeds a threshold, the API Gateway immediately returns 429 Too Many Requests or 503 Service Unavailable to Free users. We fail fast rather than hanging connections.
- Circuit Breakers:
- If a specific model service (e.g., GPT-4) starts timing out, the Chat Service trips the circuit breaker and prevents new requests to that model, potentially falling back to a default model or read-only mode.
- Stream Resiliency:
- If the network drops, the client can use the Last-Event-ID in SSE to try and resume, or simply request the full history once the connection is back.
13. Security, privacy and abuse
- Prompt Injection:
- Users might try to override safety rules ("Ignore all instructions...").
- Defense: We run inputs through a separate, lightweight Moderation Model (e.g., BERT-based) before they reach the main LLM. If it detects malicious intent, we block the request.
- PII Scrubbing:
- We run regex scrubbers to mask emails and phone numbers in the logs to prevent sensitive data from entering future training datasets.
- Rate Limiting:
- Strict Token Bucket limits per user (e.g., 50 messages / 3 hours). This is primarily for cost control, as inference is expensive.
14. Bottlenecks and next steps
- Bottleneck: Context Window Size.
- As chats get very long, passing the full history becomes too expensive and hits token limits.
- Next Step: Summarization. A background job summarizes the first half of the conversation into a paragraph and replaces the raw messages in the context with this summary.
- Bottleneck: GPU Scarcity.
- Next Step: Speculative Decoding. Use a small "draft" model to predict the next few tokens, and the large model to verify them in parallel. This speeds up inference without losing quality.
Summary
-
Architecture: Separates Chat Service (Stateful, I/O bound) from Model Gateway (Stateless, Compute bound).
-
Streaming: Uses SSE for real-time text delivery.
-
Data: Redis for hot context, DynamoDB for persistent history.
-
Key Challenge: Managing expensive GPU resources via Queuing, Tiered Access, and Caching (Semantic & KV).
On this page
1. Problem Definition and Scope
2. Clarify functional requirements
3. Clarify non-functional requirements
4. Back of the envelope estimates
5. API design
6. High level architecture
7. Data model
8. Core flows end to end
Phase 1: Ingestion & Gatekeeping (Fail Fast)
Phase 2: Context Assembly (The "Memory" Layer)
Phase 3: Orchestration (The "Waiting Room")
Phase 4: Inference & Streaming (The Execution)
Phase 5: Async Persistence (The Cleanup)
9. Caching and read performance
10. Storage, indexing and media
11. Scaling strategies
12. Reliability, failure handling and backpressure
13. Security, privacy and abuse
14. Bottlenecks and next steps
Summary